package com.zksb.controller;

import com.zksb.entity.Goods;
import com.zksb.entity.Result;
import com.zksb.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Controller
@RequestMapping("/carts")
public class CartController {

    @Autowired
    private CartService cartService;

    /**
     * 添加商品到购物车
     * 如果当前商品已经存在购物车，则增加商品数量（不会重复增加商品）
     * 如果湔商品不存在，则添加商品到购物车。
     *
     * @param request HttpServletRequest对象
     * @param goodsId      商品ID
     * @param quantity     商品数量
     * @return json
     */
    @RequestMapping("/add")
    @ResponseBody
    public Object add(HttpServletRequest request, HttpServletResponse response, Integer goodsId, Integer quantity) {
        int size = cartService.add(request, response, goodsId, quantity);
        return Result.success(size);
    }

    /**
     * 修改购物车中某个商品的数量和金额
     * @param request
     * @param goodsId 商品ID
     * @param quantity 商品数量
     * @return 购物车中的商品对象
     */
    @RequestMapping("/update")
    @ResponseBody
    public Object update(HttpServletRequest request, HttpServletResponse response, Integer goodsId, Integer quantity) {
        Goods cart = cartService.update(request, response, goodsId, quantity);
        return Result.success(cart);
    }

    /**
     * 删除购物车中的商品，返回购物车中剩余商品种类。
     * @param request HttpServletRequest对象
     * @param goodsId 商品ID
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public Object delete(HttpServletRequest request, HttpServletResponse response, Integer goodsId) {
        int size = cartService.delete(request, response, goodsId);
        return Result.success(size);
    }

    /**
     * 获取购物车，跳转到购物车页面
     * @param request Request对象
     * @return
     */
    @RequestMapping("/getCarts")
    public Object getCarts(HttpServletRequest request) {
        Map<Integer, Goods> cart = cartService.getCart(request);
        request.setAttribute("carts", cart);   //
        return "cart";
    }
}
